package com.tedu.demo;

import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

//测试暴力反射
public class Test03_Boomget {
    public static void main(String[] args) throws Exception {
        //method();
        //method2();
        method3();
    }

    public static void method3() throws Exception {
        //获取对象
        Class class1 = Preson.class;
        //获取show()方法
        Method method = class1.getMethod("show",null);
        //获取Test注解的标志
        Test test = method.getDeclaredAnnotation(Test.class);


        //有注解就运行
        Object show = class1.newInstance();
        if (test != null){
            method.invoke(show,null);
        }
    }

    public static void method() throws Exception {
        //创建class对象
        Class<Preson> class1 = Preson.class;
        //调用方法   --只能获取自己的方法  父类的没获取
        Method[]  mt = class1.getDeclaredMethods();
        for (Method a:mt){
            System.out.println(a.getName());
        }
        //触发私有方法
        Method m = class1.getDeclaredMethod("eat",String.class);
        //暴力反射除了使用对API：getDeclaredMethod    --还得开启权力
        m.setAccessible(true);

        Object obj = class1.newInstance();
        m.invoke(obj,"tony");

        //触发公开方法
        Method m1 = class1.getDeclaredMethod("game");
        m1.invoke(obj,null);
    }
    public static void method2() throws Exception {
        //获取全部变量
        Class<Preson> class2 = Preson.class;
        Field[] BL = class2.getDeclaredFields();
        for (Field a:BL){
            System.out.println(a.getName());
            System.out.println(a.getType().getName());
        }
        //获取单个变量
        Field Bl1 = class2.getDeclaredField("age");
        //设置值
        Object obj = class2.newInstance();
        Bl1.setAccessible(true);
        Bl1.set(obj,50);
        //获取值
        System.out.println(Bl1.get(obj));
        //简单获取单个属性名及属性类型
        //System.out.println(Bl1.getName());
        //System.out.println(Bl1.getType().getName());
    }
}
